<script setup lang="ts">
import {ref} from "vue"
import {useRoute} from "vue-router";
import axios from "axios";
import {loginUser, ServerHost, orderStatusEnum} from "@/main";
import {downloadImg} from "@/utils";
import dayjs from 'dayjs'

import {ElNotification, FormInstance, FormRules} from "element-plus";
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import logo from "@/assets/images/logo.svg"
import AMapLoader from "@amap/amap-jsapi-loader";
import Clipboard from "clipboard";

let map = null
let AMap = null

const route = useRoute()
const agritainmentId = route.params.id;
const agritainment = ref({
  id: "",
  name: "",
  img: "",
  introduction: "",
  contact: "",
  tel: "",
  address: "",
  posterId: "",
  lng: 110.296373, // 经度
  lat: 25.278333, // 纬度
  businessHours: "",
  addTime: new Date(),
});

const imgUrl = ref('')
const link = ref('')
link.value = window.location.href
const isLoading = ref(true)

// 获取农家乐
const loadItem = () => {
  axios.get(`${ServerHost}/getAgritainment?id=${agritainmentId}`)
      .then((res) => {
        if (res.status === 200) {
          console.log(res.data)
          agritainment.value = res.data
          // 更新标题
          document.title = `${agritainment.value.name} - 乡兴助农`;
          //  处理换行符
          agritainment.value.introduction = agritainment.value.introduction.replace(/\n/g, '<br>')
          // 加载高德地图
          AMapLoader.load({
            key: "225ab1a1758d7eed67798492e1c6263e",
            version: "2.0",
            plugins: [
              "AMap.Geolocation", // 启用定位组件
            ],
          }).then((mAMap) => {
            const position = [agritainment.value.lng, agritainment.value.lat]
            AMap = mAMap
            map = new AMap.Map('detail-map', {
              center: position, // 设置地图中心点为农家乐坐标
              zoom: 14,
            });
            map.addControl(new AMap.Geolocation());

            // 添加农家乐坐标标记
            const marker = new AMap.Marker({
              position: position,
            })
            map.add(marker)

            // 将农家乐名称显示在地图
            const text = new AMap.Text({
              text: agritainment.value.address, //标记显示的文本内容
              anchor: "bottom-center", //设置文本标记锚点位置
              cursor: "pointer", //指定鼠标悬停时的鼠标样式。
              offset: [0, -36],
              position: position,
              style: {
                fontSize: '0.8rem',
              }
            });
            text.setMap(map); //将文本标记设置到地图上
          }).catch(e => {
            console.log(e);
          })
        }
        downloadImg(agritainment.value.img, "agritainmentImg/")
            .then(res => {
              if (res.status === 200) {
                const type = 'image/png'
                const blob = new Blob([res.data], {type: type})
                const imgFile = new File([blob], agritainment.value.img, {type: type})
                imgUrl.value = URL.createObjectURL(imgFile)
                isLoading.value = false
              }
            })
      })
}
loadItem();


let clipboard = new Clipboard("#copyLinkBtn");
const onCopyLink = () => {
  console.log(link.value)
  clipboard.on("success", function (e) {
    ElNotification({
      title: '复制成功，可以分享了',
      type: 'success',
      position: 'bottom-right',
    })
    e.clearSelection();
  })
  clipboard.on("error", function (e) {
    ElNotification({
      title: '复制失败',
      type: 'success',
      position: 'bottom-right',
    })
    e.clearSelection();
  })
}

</script>

<template>
  <el-card class="m-2" v-loading="isLoading">
    <template #header>
      <div class="flex justify-center gap-2">
        <img class="cover-img" :src="imgUrl" alt="image">
        <div class="flex flex-col justify-between">
          <div class="flex flex-col gap-2">
            <p class="name">{{ agritainment.name }}</p>
            <p class="info"> {{ dayjs(agritainment.addTime).format('YYYY/MM/DD HH:mm:ss') }}</p>
            <p class="address">{{ agritainment.address }}</p>

          </div>
          <div class="flex flex-col gap-2">
          </div>
        </div>
      </div>

    </template>

    <div class="flex flex-col justify-center gap-4">
      <div>
        <el-tag size="large">农家乐介绍</el-tag>
        <p v-html="agritainment.introduction"/>

      </div>
      <div>
        <el-tag size="large">联系方式</el-tag>
        <p>{{ agritainment.contact }} {{ agritainment.tel }}</p>
      </div>

      <div>
        <el-tag size="large">营业时间</el-tag>
        <p>{{ agritainment.businessHours }}</p>
      </div>

      <div>
        <el-tag size="large">农家乐位置</el-tag>
        <div id="detail-map" class="mt-1"/>
      </div>
    </div>


    <template #footer>
      <el-button @click="onCopyLink">复制链接</el-button>
      <el-popover
          placement="top-start"
      >
        <template #default>
          <vue-qr
              :text="link"
              :logoSrc="logo"
              colorDark="#33B173"/>
        </template>
        <template #reference>
          <el-button>前往手机浏览</el-button>
        </template>
      </el-popover>

    </template>
  </el-card>
</template>

<style scoped lang="scss">
#detail-map {
  width: 100%;
  max-width: 900px;
  aspect-ratio: 16/9;
  border-radius: 4px;
}

.name {
  font-size: 1.3rem;
  font-family: "思源宋体 Heavy", serif;
  color: var(--el-color-primary);
}

.info {
  font-size: 0.9rem;
  color: var(--el-color-info);
}

.cover-img {
  width: 400px;
  height: 400px;
  border-radius: 8px;
  object-fit: cover;
}

.address {
  font-size: 0.8rem;
}
</style>
